__author__ = 'Muscle'

import traceback
import os
import mui.InternalUse.muiconfig as muiconfig
import mui.CExt.muiDX as DX

class TextureResource(object):
    def __init__(self, filename, dxDevice):
        self._dxDevice = dxDevice
        self._path = findResource(filename)
        self._texture = None

    def __del__(self):
        if self._texture != None:
            self._texture.Release()
            self._texture = None

    def __getTexture(self):
        try:
            if (self._texture == None):
                self._texture = DX.CDXTexture2D(self._dxDevice)
                self._texture.LoadFromFile(unicode(self._path))
            return self._texture
        except Exception, e:
            traceback.print_exc()
            return None

    texture = property(__getTexture)


class ResourceManager(object):
    def __init__(self):
        self._textureResources = {}

    def getTexture(self, path, dxDevice):
        _path, borderW  = self._preprocessPath(path)

        if (not self._textureResources.has_key(dxDevice)):
            self._textureResources[dxDevice] = {}
        if (not self._textureResources[dxDevice].has_key(_path)):
            texResource = TextureResource(_path, dxDevice)
            self._textureResources[dxDevice][_path] = texResource
        return (self._textureResources[dxDevice][_path], borderW)

    def _preprocessPath(self, path):
        filePath, sep, borderStr = path.partition('|')
        filePath = filePath.lower()
        filePath = filePath.strip(' ')
        borderW = tuple()
        if (not borderStr):
            pass
        else:
            borderStr = borderStr.strip(' ')
            borderStr = borderStr.strip('(')
            borderStr = borderStr.strip(')')
            lw, tw, rw, bw = borderStr.split(',')
            borderW = (int(lw), int(tw), int(rw), int(bw))

        return (filePath, borderW)

    def clearResource(self):
        self._textureResources.clear()

g_resourceManager = ResourceManager()

def getTextureResource(path, dxDevice):
    return g_resourceManager.getTexture(path, dxDevice)

def clearResource():
    g_resourceManager.clearResource()

def findResource(localPath):
    if (os.path.exists(localPath)):
        return localPath
    absPath = os.path.abspath(localPath)
    if (os.path.exists(absPath)):
        return absPath
    for _dir in muiconfig.g_ResourceDirs:
        if os.path.exists(_dir + "\\" + localPath):
            retPath = _dir + "\\" + localPath
            return retPath
    return None